import isEmpty from "lodash/isEmpty";
import {
  message
} from "antd";
import {
  indexOf
} from "lodash";

const dbKeys = [
  "PERCENT",
  "PLAN",
  "PRECISION",
  "PRIMARY",
  "PRINT",
  "PROC",
  "PROCEDURE",
  "PUBLIC",
  "RAISERROR",
  "READ",
  "READTEXT",
  "RECONFIGURE",
  "REFERENCES",
  "REPLICATION",
  "RESTORE",
  "RESTRICT",
  "RETURN",
  "REVOKE",
  "RIGHT",
  "ROLLBACK",
  "ROWCOUNT",
  "ROWGUIDCOL",
  "RULE",
  "SAVE",
  "SCHEMA",
  "SELECT",
  "SESSION_USER",
  "SET",
  "SETUSER",
  "SHUTDOWN",
  "SOME",
  "STATISTICS",
  "SYSTEM_USER",
  "TABLE",
  "TEXTSIZE",
  "THEN",
  "TO",
  "TOP",
  "TRAN",
  "TRANSACTION",
  "TRIGGER",
  "TRUNCATE",
  "TSEQUAL",
  "UNION",
  "UNIQUE",
  "UPDATE",
  "UPDATETEXT",
  "USE",
  "USER",
  "VALUES",
  "VARYING",
  "VIEW",
  "WAITFOR",
  "WHEN",
  "WHERE",
  "WHILE",
  "WITH",
  "WRITETEXT",
  "EXCEPT",
  "EXEC",
  "EXECUTE",
  "EXISTS",
  "EXIT",
  "FETCH",
  "FILE",
  "FILLFACTOR",
  "FOR",
  "FOREIGN",
  "FREETEXT",
  "FREETEXTTABLE",
  "FROM",
  "FULL",
  "FUNCTION",
  "GOTO",
  "GRANT",
  "GROUP",
  "HAVING",
  "HOLDLOCK",
  "IDENTITY",
  "IDENTITY_INSERT",
  "IDENTITYCOL",
  "IF",
  "IN",
  "INDEX",
  "INNER",
  "INSERT",
  "INTERSECT",
  "INTO",
  "IS",
  "JOIN",
  "KEY",
  "KILL",
  "LEFT",
  "LIKE",
  "LINENO",
  "LOAD",
  "NATIONAL",
  "NOCHECK",
  "NONCLUSTERED",
  "NOT",
  "NULL",
  "NULLIF",
  "OF",
  "OFF",
  "OFFSETS",
  "ON",
  "OPEN",
  "OPENDATASOURCE",
  "OPENQUERY",
  "OPENROWSET",
  "OPENXML",
  "OPTION",
  "OR",
  "ORDER",
  "OUTER",
  "OVER",
  "ADD",
  "ALL",
  "ALTER",
  "AND",
  "ANY",
  "AS",
  "ASC",
  "AUTHORIZATION",
  "BACKUP",
  "BEGIN",
  "BETWEEN",
  "BREAK",
  "BROWSE",
  "BULK",
  "BY",
  "CASCADE",
  "CASE",
  "CHECK",
  "CHECKPOINT",
  "CLOSE",
  "CLUSTERED",
  "COALESCE",
  "COLLATE",
  "COLUMN",
  "COMMIT",
  "COMPUTE",
  "CONSTRAINT",
  "CONTAINS",
  "CONTAINSTABLE",
  "CONTINUE",
  "CONVERT",
  "CREATE",
  "CROSS",
  "CURRENT",
  "CURRENT_DATE",
  "CURRENT_TIME",
  "CURRENT_TIMESTAMP",
  "CURRENT_USER",
  "CURSOR",
  "DATABASE",
  "DBCC",
  "DEALLOCATE",
  "DECLARE",
  "DEFAULT",
  "DELETE",
  "DENY",
  "DESC",
  "DISK",
  "DISTINCT",
  "DISTRIBUTED",
  "DOUBLE",
  "DROP",
  "DUMMY",
  "DUMP",
  "ELSE",
  "END",
  "ERRLVL",
  "ESCAPE",
  "ACCESS",
  "ADD",
  "ALL",
  "ALTER",
  "AND",
  "ANY",
  "AS",
  "ASC",
  "AUDIT",
  "BETWEEN",
  "BY",
  "CHAR",
  "CHECK",
  "CLUSTER",
  "COLUMN",
  "COMMENT",
  "COMPRESS",
  "CONNECT",
  "CREATE",
  "CURRENT",
  "DATE",
  "DECIMAL",
  "DEFAULT",
  "DELETE",
  "DESC",
  "DISTINCT",
  "DROP",
  "ELSE",
  "EXCLUSIVE",
  "EXISTS",
  "FILE",
  "FLOAT",
  "FOR",
  "FROM",
  "GRANT",
  "GROUP",
  "HAVING",
  "IDENTIFIED",
  "IMMEDIATE",
  "IN",
  "INCREMENT",
  "INDEX",
  "INITIAL",
  "INSERT",
  "INTEGER",
  "INTERSECT",
  "INTO",
  "IS",
  "LEVEL",
  "LIKE",
  "LOCK",
  "LONG",
  "MAXEXTENTS",
  "MINUS",
  "MLSLABEL",
  "MODE",
  "MODIFY",
  "NOAUDIT",
  "NOCOMPRESS",
  "NOT",
  "NOWAIT",
  "NULL",
  "NUMBER",
  "OF",
  "OFFLINE",
  "ON",
  "ONLINE",
  "OPTION",
  "OR",
  "ORDER",
  "PCTFREE",
  "PRIOR",
  "PRIVILEGES",
  "PUBLIC",
  "RAW",
  "RENAME",
  "RESOURCE",
  "REVOKE",
  "ROW",
  "ROWID",
  "ROWNUM",
  "ROWS",
  "SELECT",
  "SESSION",
  "SET",
  "SHARE",
  "SIZE",
  "SMALLINT",
  "START",
  "SUCCESSFUL",
  "SYNONYM",
  "SYSDATE",
  "TABLE",
  "THEN",
  "TO",
  "TRIGGER",
  "UID",
  "UNION",
  "UNIQUE",
  "UPDATE",
  "USER",
  "VALIDATE",
  "VALUES",
  "VARCHAR",
  "VARCHAR2",
  "VIEW",
  "WHENEVER",
  "WHERE",
  "WITH"
];

export const validate = (conditions, params = {}) => {
  if (!isEmpty(conditions)) {
    for (let i = 0, leg = conditions.length; i < leg; i++) {
      let cd = conditions[i];
      for (let j = 0, length = cd.items.length; j < length; j++) {
        let c = cd.items[j];
        if (c) {
          let domkey = c.domkey[0];
          let viewAttr = c.viewAttr;
          if (c.conditionType == "BROWSER")
            viewAttr = c.browserConditionParam.viewAttr;
          if (viewAttr == "3" && !params[domkey]) {
            if (domkey == "managerid" || domkey == "belongto") {
              //直接上级 主账号不用校验
            } else {
              //message.warning(domkey+'必要信息不完整！');
              message.warning("必要信息不完整！");
              return false;
            }
          }
        }
      }
    }
  }
  return true;
};

export const getFormParamValue = (conditions = {}, fieldname) => {
  let fieldvalue = "";
  if (!isEmpty(conditions)) {
    for (let i = 0, leg = conditions.length; i < leg; i++) {
      let cd = conditions[i];
      for (let j = 0, length = cd.items.length; j < length; j++) {
        let c = cd.items[j];
        if (c) {
          let domkey = c.domkey[0];
          if (domkey == fieldname) {
            fieldvalue = c.value;
          }
        }
      }
    }
  }
  return fieldvalue;
};

export const transParams = formParams => {
  let params = {};
  for (let key in formParams) {
    if (formParams[key] === !!formParams[key])
      params[key] = !!formParams[key] ? "1" : "0";
    else params[key] = formParams[key];
  }
  return params;
};

export const findTabCount = str => {
  const bIndex = str.lastIndexOf("(");
  const eIndex = str.lastIndexOf(")");
  let title = "",
    count = "";
  try {
    title = str.substring(0, bIndex);
    count = str.substring(bIndex + 1, eIndex);
  } catch (err) {}
  return {
    title,
    count
  };
};

export const calFormHeight = (groupLength, children) => {
  let childrenLength = 0;
  children.map(c => {
    if (c.colSpan != null) {
      childrenLength += c.colSpan == 2 ? 1 : 2;
    } else childrenLength += 1;
  });
  let height = (childrenLength / 2 + (childrenLength % 2)) * 52 + 10;
  if (groupLength > 1) height += groupLength * 45;
  if (height > 300) return 300;
  return height;
};

export const validDBKeys = value => {
  if (indexOf(dbKeys, value.toUpperCase()) >= 0) {
    message.error("不能使用数据库保留字作为字段名!");
    return {
      isValid: false,
      value: ""
    };
  }
  return {
    isValid: true,
    value
  };
};

export const validNumber = value => {
  if (isNaN(parseInt(value))) return 0;
  return parseInt(value);
};

export const getColumIndex = num => {
  const n = 64;
  const loopIndex = num / 26;
  if (loopIndex <= 1)
    return String.fromCharCode(n + (num % 26 === 0 ? 26 : num));
  else
    return `${String.fromCharCode(
      n + parseInt(loopIndex)
    )}${String.fromCharCode(n + (num % 26))}`;
};

export const calColumnIndex = val => {
  const arr = Array.from(val);
  let num = 0;
  if (arr.length === 1) num = arr[0].charCodeAt() - 64;
  else {
    arr.map((c, i) => {
      if (i === 0) num += (c.charCodeAt() - 64) * 26;
      else num += c.charCodeAt() - 64;
    });
  }

  return num;
};

export const convertCalendarDate = date => {
  const y = date.getYear();
  let d = date.getDayOfMonth();
  if (d < 10) d = "0" + d;
  let m = date.getMonth() + 1;
  if (m < 10) m = "0" + m;
  return `${y}-${m}-${d}`;
};

export const dateFormat = (date, format) => {
  let o = {
    "M+": date.getMonth() + 1, //month
    "d+": date.getDate(), //day
    "h+": date.getHours(), //hour
    "m+": date.getMinutes(), //minute
    "s+": date.getSeconds(), //second
    "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
    S: date.getMilliseconds() //millisecond
  };
  if (/((y|Y)+)/.test(format))
    format = format.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(format))
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return format;
};

import {
  WeaLocaleProvider
} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
/**
  正常
  迟到
  早退
  旷工
  漏签
  请假
  出差
  公出
  加班
  异常数据抵扣
 */
// NORMAL,BELATE,LEAVEEARLY,ABSENT,NOSIGN,LEAVE,EVECTION,OUTDAYS,OVERTIME,OTHER;

export const getIcon = type => {
  let res = {};
  if (type == 'LEAVE') {
    res.color = '#2DB7F5';
    res.icon = 'icon-Human-resources-leave';
  }
  if (type == 'EVECTION') {
    res.color = '#48C651';
    res.icon = 'icon-Human-resources-business-travel';
  }
  if (type == 'OUTDAYS') {
    res.color = '#4F8CFF';
    res.icon = 'icon-Human-resources-work';
  }
  if (type == 'OVERTIME') {
    res.color = '#8D6BF3';
    res.icon = 'icon-Human-resources-overtime';
  }
  if (type == 'OTHER') {
    res.color = '#ABB4C1';
    res.icon = 'icon-Human-resources-abnormal-small2';
  }
  return res;
}

export const getIconColor = type => {
  let res = {};
  if (type == 'ALL') {
    res.color = '#2DB7F5';
    res.name = (window.e9_locale.userLanguage == "8") ?  "All type" : getLabel(82857, '全部');
    res.icon = 'icon-Human-resources-all';
  }
  if (type == 'NORMAL') {
    res.color = '#2DB7F5';
    res.name = getLabel('225', "正常");
    res.icon = 'icon-Human-resources-normal';
  }
  if (type == 'BELATE') {
    res.color = '#FF8F00';
    res.name = getLabel('20081', "迟到");
    res.bcolor = '#FFF6EB';
    res.icon = 'icon-Human-resources-late';
  }
  if (type == 'LEAVEEARLY') {
    res.color = '#7326FF';
    res.name = getLabel('20082', "早退");
    res.bcolor = '#F1E9FF';
    res.icon = 'icon-Human-resources-Leave-early';
  }
  if (type == 'ABSENT') {
    res.color = '#FC4B6C';
    res.name = (window.e9_locale.userLanguage == "8") ? "Truancy" : getLabel('20085', "旷工");
    res.bcolor = '#FFE6EB';
    res.icon = 'icon-Human-resources-Absenteeism';
  }
  if (type == 'NOSIGN') {
    res.color = '#BD10E0';
    res.name = (window.e9_locale.userLanguage == "8") ? "Forget" :getLabel('20086', "漏签");
    res.bcolor = '#FAECFD';
    res.icon = 'icon-Human-resources-check';
  }
  if (type == 'LEAVE') {
    res.color = '#2DB7F5';
    res.name = (window.e9_locale.userLanguage == "8") ? "Leave" : getLabel('670', "请假");
    res.bcolor = '#EFFAFF';
    res.icon = 'icon-Human-resources-leave';
  }
  if (type == 'EVECTION') {
    res.color = '#30BE3A';
    res.name = (window.e9_locale.userLanguage == "8") ? "Business Trip" :getLabel('20084', "出差");
    res.bcolor = '#EFFAF0';
    res.icon = 'icon-Human-resources-business-travel';
  }
  if (type == 'OUTDAYS') {
    res.color = '#4F8CFF';
    res.name =(window.e9_locale.userLanguage == "8") ? "Business Out" : getLabel('24058', "公出");
    res.bcolor = '#DFEBFF';
    res.icon = 'icon-Human-resources-work';
  }
  if (type == 'OVERTIME') {
    res.color = '#8D6BF3';
    res.name = getLabel('6151', "加班");
    res.bcolor = '#FAECFD';
    res.icon = 'icon-Human-resources-overtime-small';
  }
  if (type == 'OTHER') {
    res.color = '#ABB4C1';
    res.name = getLabel('32104', "异常");
    res.title = getLabel('132031', "异常数据抵扣");
    res.bcolor = '#F0F6FF';
    res.icon = 'icon-Human-resources-abnormal-small2';
  }
  return res;
}

export const createQRCode = data => {
  //生成二维码
  var txt = "BEGIN:VCARD \n" +
    "VERSION:3.0 \n" +
    "N:" + data.lastname + " \n" +
    "TEL;CELL;VOICE:" + data.mobile + "\n" +
    "TEL;WORK;VOICE:" + data.telephone + "\n" +
    "EMAIL:" + data.email + " \n" +
    "TITLE:" + data.jobtitle + " \n" +
    "ROLE:" + data.department + "\n" +
    "ADR;WORK:" + data.locationname + " \n" +
    "END:VCARD";
  return utf16to8(txt);

  function utf16to8(str) {
    var out, i, len, c;
    out = "";
    len = str.length;
    for (i = 0; i < len; i++) {
      c = str.charCodeAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        out += str.charAt(i);
      } else if (c > 0x07FF) {
        out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
        out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      } else {
        out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
      }
    }
    return out;
  }
}

// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
export const DateFormat = (date, fmt) => {
  if (date && fmt) {
    let _this = date
    const type = Object.prototype.toString.call(date)
    if (type == "[object String]") {
      let dateArray = date.split(" "),
        d1 = dateArray[0].split("-"),
        d2 = dateArray[1] ? dateArray[1].split(":") : [];
      _this = new Date((d1[0] || 0) * 1, (d1[1] || 0) * 1 - 1, (d1[2] || 0) * 1, (d2[0] || 0) * 1, (d2[1] || 0) * 1, (d2[2] || 0) * 1)
    } else if (type == "[object Date]") {

    } else {
      return ""
    }
    let o = {
      "M+": _this.getMonth() + 1, //月份
      "d+": _this.getDate(), //日
      "h+": _this.getHours() % 12 == 0 ? 12 : _this.getHours() % 12, //小时
      "H+": _this.getHours(), //小时
      "m+": _this.getMinutes(), //分
      "s+": _this.getSeconds(), //秒
      "q+": Math.floor((_this.getMonth() + 3) / 3), //季度
      "S": _this.getMilliseconds() //毫秒
    };
    let week = {
      "0": "\\u65e5",
      "1": "\\u4e00",
      "2": "\\u4e8c",
      "3": "\\u4e09",
      "4": "\\u56db",
      "5": "\\u4e94",
      "6": "\\u516d"
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (_this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
      let weekStr = ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\\u661f\\u671f" : "\\u5468") : "") + week[_this.getDay() + ""]
      fmt = fmt.replace(RegExp.$1, Utils.GB2312UnicodeConverter.ToGB2312(weekStr));
    }
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  } else {
    return ""
  }
}

export const IEVersion = () => {
    let userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
    let isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
    let isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
    let isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if(isIE) {
        let reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        let fIEVersion = parseFloat(RegExp["$1"]);
        if(fIEVersion == 7) {
            return 7;
        } else if(fIEVersion == 8) {
            return 8;
        } else if(fIEVersion == 9) {
            return 9;
        } else if(fIEVersion == 10) {
            return 10;
        } else {
            return 6;//IE版本<=7
        }   
    } else if(isEdge) {
        return 'edge';//edge
    } else if(isIE11) {
        return 11; //IE11  
    }else{
        return -1;//不是ie浏览器
    }
}

